<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\logic\AdminLogic;
use think\facade\Env;
use think\facade\Response;

class Upload extends AdminController
{
    public function initialize(){
        $this->noCheckAction = ['check_file_md5','upload'];
        parent::initialize();
    }
    /**
     * 检测文件是否存在
     */
    public function check_file_md5(){
        $hash = input('hash');
        if(empty($hash)){
            $this->error('未找到',null,[]);
        }
        $alj = new AdminLogic();
        $model = $alj->_getAttachmentByHash($hash);
        if(empty($model)){
            $this->error('未找到',null,[]);
        }
        else{
            $base_url = Env::get('LOCAL_BASE_URL');
            $this->success('成功',null,[
                'title' => $model['title'],
                'dir' => $model['dir'],
                'ext' => $model['ext'],
                'size' => $model['size'],
                'url' => $base_url . $model['dir'] . $model['title'],
            ]);
        }

    }
    /**
     * 上传文件
     */
    public function upload()
    {
        $source = $this->request->param('source');
        switch ($source) {
            case 'file_delete_empty':
                // 删除文件，假删除
                return [
                    'error' => '',
                ];
                break;
            case 'file_delete':
                // 删除文件，需要传送文件名过来
                return $this->file_delete();
                break;
            case 'file-input':
                $this->fileInputUpload();
                break;
            case 'um-editor':
                $this->umEditorUpload();
                break;
            case 'summer-note':
            default:
                $this->normalUpload();
        }
    }

    /**
     * FileInput上传
     */
    protected function fileInputUpload()
    {
        if (!isset($_FILES['file_data'])) {
            $this->error('上传文件不存在');
        }

        $jieguo = $this->doUploadFormData('file_data');
        if($jieguo['err_code'] !== 0){
            echo json_encode([
                'error' => $jieguo['msg']
            ]);
        }
        else{
            $this->success('上传成功','',$jieguo['data']);
        }
    }

    protected function file_delete(){
        $key = input('key');
        if (empty($key)) {
            return [
                'error' => '参数未传',
            ];
        }

        $alj = new AdminLogic();
        if($alj->_delAttachment($key) !== false){
            return [
                'error' => '',
            ];
        }
        else{
            return [
                'error' => '删除失败',
            ];
        }
    }

    /**
     * UmEditor上传
     */
    protected function umEditorUpload()
    {
        if (!isset($_FILES['upfile'])) {
            $data = [
                'state' => '上传文件为空'
            ];
            echo json_encode(json_encode($data));
        }

        $jieguo = $this->doUploadFormData('upfile');
        if($jieguo['err_code'] !== 0){
            echo json_encode([
                'state' => $jieguo['msg']
            ]);
        }
        else{
            echo json_encode([
                'state' => 'SUCCESS',
                'url' => $jieguo['data']['url'],
                'title' => $jieguo['data']['title'],
                'original' => $jieguo['data']['title'],
            ]);
        }
    }

    /**
     * 普通上传
     */
    protected function normalUpload()
    {
        if (!isset($_FILES['upload_file'])) {
            $this->error('上传文件为空');
        }

        $uploadFile = $_FILES['upload_file'];
        $this->response($this->doUpload($uploadFile));
    }

    /**
     * 上传文件
     *
     * @param array $uploadFile
     */
    protected function doUploadFormData($fileName)
    {
        $file = request()->file($fileName);
        if(empty($file)){
            return [
                'err_code' => 1,
                'msg' => '文件为空',
                'data' => [],
            ];
        }
        $base_url = Env::get('LOCAL_BASE_URL');
        $base_path = Env::get('ROOT_PATH') . '/public' . Env::get('LOCAL_DIR');
        // 移动到框架应用根目录/uploads/ 目录下
        $size = (10 * 1024 * 1024);
        $ext = 'jpg,png,gif';
        $info = $file->rule('date')->validate(['size'=>$size,'ext'=>$ext])->move($base_path);
        if($info){
//            // 成功上传后 获取上传信息
            // 入库
            $saveFileName = explode(DIRECTORY_SEPARATOR,$info->getSaveName());
            $oldInfo = $info->getInfo();
            $alj = new AdminLogic();
            $alj->_addAttachment([
                'uid' => $this->adminId,
                'filename' => $oldInfo['name'],
                'title' => $info->getFilename(),
                'size' => $info->getSize(),
                'dir' => '/' . $saveFileName[0] . '/',
                'md5' => $info->hash('md5'),
                'type' => $info->getMime(),
                'ext' => $info->getExtension(),
                'create_time' => time(),
            ]);

            return [
                'err_code' => 0,
                'msg' => '成功',
                'data' => [
                    'url' => ($base_url . '/' . $info->getSaveName()),
                    'ext' => $info->getExtension(),
                    'md5' => $info->hash('md5'),
                    'title' => $info->getFilename(),
                ],
            ];
        }else{
            // 上传失败获取错误信息
            $info = $file->getInfo();
            return [
                'err_code' => 1,
                'msg' => $info['name'] . ' ' . $file->getError(),
                'data' => [],
            ];
        }


    }

}